package tx.core;

import java.awt.Image;
import java.util.HashMap;
import java.util.Map;

import javax.swing.ImageIcon;

import tx.core.graphics.Animation;
import tx.core.graphics.Sprite;
import tx.development.Development;

/**
 * The unit of a tetraminoe. 
 * @author Guilherme Mauro Germoglio Barbosa - germoglio@gmail.com
 */
public class Block extends Sprite {

	public static final float GRAVITY = .002f;
	
	/**
	 * A cache of images of the blocks, in order to spare memory.
	 */
	private static Map<Integer, Image> imageCache = new HashMap<Integer, Image>();
	
	/**
	 * If the block is desapearing (when it was cleared) or not.
	 */
	private boolean isDisapearing;

	/**
	 * If the block is going down and accelerating.
	 */
	private boolean isGoingDown;
	


	/**
	 * Creates a Block, given the animation it will use.
	 * @param animation The animation it will use.
	 */
	private Block(Animation animation) {
		super(animation);
	}

	/**
	 * Creates a Block, given the color it will use.
	 * @param color The color of the Block
	 * @return A Block.
	 */
	public static Block createBlock(int color) {
		
		if (Development.DEBUG_ENABLED) System.out.println(Development.DEBUG_LABEL + "Block.createBlock()" + "Block Image file: " + BlockColors.BLOCK_IMAGE_PREFIX + getColorFileName(color) + BlockColors.BLOCK_IMAGE_SUFIX);
		
		Animation animation = new Animation();
		Block block = new Block(animation);
		Image image = imageCache.get(color);
		if (image == null) {
			image = new ImageIcon(block.getClass().getResource(BlockColors.BLOCK_IMAGE_PREFIX + getColorFileName(color) + BlockColors.BLOCK_IMAGE_SUFIX)).getImage();
			imageCache.put(color, image);
		}
		animation.addFrame(image, Long.MAX_VALUE);
		return block;
	}

	/**
	 * Returns the base name matching to color.
	 * @param color The color.
	 * @return The base name of the file matching.
	 */
	private static String getColorFileName(int color) {
		
		switch(color) {
			case BlockColors.BLUE: return BlockColors.BLUE_FILE_NAME;
			case BlockColors.CYAN: return BlockColors.CYAN_FILE_NAME;
			case BlockColors.GREEN: return BlockColors.GREEN_FILE_NAME;
			case BlockColors.ORANGE: return BlockColors.ORANGE_FILE_NAME;
			case BlockColors.PINK: return BlockColors.PINK_FILE_NAME;
			case BlockColors.RED: return BlockColors.RED_FILE_NAME;
			case BlockColors.YELLOW: return BlockColors.YELLOW_FILE_NAME;
			default: throw new IllegalArgumentException("INVALID COLOR!");
		}
	}

	/* (non-Javadoc)
	 * @see tx.core.graphics.Sprite#update(long)
	 */
	public void update(long elapsedTime) {
		if (Development.DEBUG_ENABLED) System.out.println(Development.DEBUG_LABEL +  "Block.update() " + elapsedTime);
		
		if (this.isGoingDown) {
            setVelocityY(getVelocityY() + GRAVITY * elapsedTime);
        }
		
		super.update(elapsedTime);
	}

	/**
	 * Makes the block goes down, and accelarating.
	 */
	public void goDown() {
		this.isGoingDown = true;
	}
	
}
